import random
from django_redis import get_redis_connection

# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from apps.users.serializer import RegisterSerializer, LoginSerializer
from celery_tasks.sms.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import send_sms_code


# 获取短信验证码
class SMSCodeView(APIView):
    ''' GET /sms_codes/{mobile}/'''
    def get(self, request, mobile):

        redis_conn = get_redis_connection('verify')
        flag = redis_conn.get('flag_%s' % mobile)
        if flag:
            return Response({'success': False, 'message': '反复发送短信'})
        # 生成验证码
        sms_code = random.randint(0, 999999)
        sms_code = '%06d' % sms_code
        print(sms_code)
        # 保存到redis
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('flag_%s' % mobile, 60, 1)
        pl.execute()

        # 异步发送短信
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        send_sms_code.delay(mobile, sms_code)

        return Response({'success': True, 'sms_code': sms_code, 'message': '短信获取成功'})


# 注册
class RegisterView(APIView):
    '''POST users/'''
    def post(self, request):
        ser = RegisterSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()

        # print(ser.data)
        return Response(ser.data, status=status.HTTP_201_CREATED)


# 登录
class LoginView(APIView):
    '''POST authorizations/'''
    def post(self, request):

        ser = LoginSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return Response(ser.data, status=status.HTTP_200_OK)

